<template>
  <div class="content">
    <div class="body-content">
      <div class="left-content">
        <el-form :model="form" label-width="auto" style="max-width: 600px">
          <div style="width: 350px; margin: 15px">
            <h1 style="display: flex; justify-content: center; width: 400px">
              注册
            </h1>
            <!-- 账号密码 -->

            <el-input
              v-model="form.teacherAccount"
              style="width: 340px; margin-bottom: 30px; height: 50px"
              size="large"
              placeholder="请输入工号/学号"
              clearable
            />
            <el-input
              v-model="form.teacherPassword"
              style="width: 340px; height: 50px; margin-bottom: 30px"
              size="large"
              type="password"
              placeholder="请输入密码"
              show-password
            />
            <el-input
              v-model="form.checkPassword"
              style="width: 340px; height: 50px"
              size="large"
              type="password"
              placeholder="请再次输入密码"
              show-password
            />
          </div>
          <!-- 验证码 -->
          <div style="width: 350px; margin: 10px">
            <el-input
              v-model="form.teacherEmail"
              style="width: 340px; margin-bottom: 30px; height: 50px"
              size="large"
              placeholder="请输入手机号/邮箱号"
              clearable
            >
              <template #append>
                <el-button
                  :disabled="isCountingDown"
                  @click="getVerificationCode(form.teacherEmail)"
                  style="height: 50px; border: 1px solid #808080"
                  :style="{
                    backgroundColor: buttonBgColor,
                    color: buttonTextColor,
                  }"
                >
                  {{ buttonText }}
                </el-button>
              </template>
            </el-input>
            <el-input
              v-model="form.code"
              style="width: 200px; height: 50px"
              size="large"
              placeholder="请输入验证码"
              clearable
            >
            </el-input>
            <router-link
              to="/"
              style="
                margin-left: 35px;
                color: #4caf50;
                font-size: 18px;
                text-decoration: none;
              "
            >
              登录
            </router-link>
          </div>

          <div>
            <el-button
              type="success"
              size="large"
              style="width: 340px; font-size: 20px"
              @click="register(form)"
              >注册</el-button
            >
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { registerUsingPost, sendVerificationEmailUsingPost } from '@/api/teacherManagementModule';
import { ElMessage } from 'element-plus';
import { onUnmounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router';
//获取的数据
const router = useRouter();
const form = reactive<API.TeacherRegisterRequest>({
    /** 确认密码 */
    checkPassword: '',
    /** 验证码 */
    code: '',
    /** 账号 */
    teacherAccount: '', 
    /** 邮箱 */
    teacherEmail: '',
    /** 密码 */
    teacherPassword: '',
});
//获取验证码
// 定义状态变量
const buttonBgColor = ref("var(--el-color-success)");
const buttonTextColor = ref("#fff");
const isCountingDown = ref(false);
const countdown = ref(120);
const buttonText = ref("获取验证码");
const timer = ref<number>(); // 保存定时器 ID，用于组件卸载时清理

// 组件卸载时清除定时器
onUnmounted(() => {
  if (timer.value) clearInterval(timer.value);
});

// 格式化时间为 MM:SS
const formatTime = (seconds: number) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes.toString().padStart(2, "0")}:${remainingSeconds
    .toString()
    .padStart(2, "0")}`;
};

// 发送验证码请求
const handleGetCode = async (email: string) => {
  try {
    const res = await sendVerificationEmailUsingPost({ email });
    if (res.data.code === 0) {
      ElMessage.success("验证码已发送");
    } else {
      throw new Error(res.data.message || "验证码发送失败");
    }
  } catch (error) {
    ElMessage.error("验证码发送失败");
    throw error; // 抛出错误，让外层捕获
  }
};

// 开始倒计时
const startCountdown = () => {
  isCountingDown.value = true;
  buttonBgColor.value = "#fff";
  buttonTextColor.value = "#999";
  buttonText.value = formatTime(countdown.value);

  timer.value = window.setInterval(() => {
    countdown.value--;
    buttonText.value = formatTime(countdown.value);
    if (countdown.value <= 0) {
      clearInterval(timer.value!);
      resetCountdown();
    }
  }, 1000);
};

// 重置倒计时状态
const resetCountdown = () => {
  isCountingDown.value = false;
  countdown.value = 120;
  buttonText.value = "获取验证码";
  buttonBgColor.value = "var(--el-color-success)";
  buttonTextColor.value = "#fff";
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = undefined;
  }
};

// 点击获取验证码
const getVerificationCode = async (email: string) => {
  if (isCountingDown.value) return;

  // 立即开始倒计时
  startCountdown();

  try {
    // 发送验证码请求（在后台进行，不影响倒计时显示）
    await handleGetCode(email);
  } catch (error) {
    // 请求失败时保持倒计时继续，但可以给用户提示
    ElMessage.error("验证码发送失败，请稍后再试");
    // 如果你想在发送失败时停止倒计时，可以调用 resetCountdown()
    // resetCountdown();
  }
};

//接收后端接口
const register = async (value: API.TeacherRegisterRequest) => {
  const res = await registerUsingPost(value);
  if (res.data.code === 0 && res.data.data) {
    ElMessage({
      message: "注册成功",
      type: "success",
    });
    router.push({
      path: "/login",
      replace: true,
    });
  } else {
    ElMessage.error("注册失败");
  }
}
</script>

<style>
.content {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.body-content {
  width: 500px;
  height: 580px;
  background-color: #fff;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.2);
  display: flex;
  justify-content: center;
}

.left-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.left-content > * {
  margin: 10px;
  /* 给 div 下的所有直接子元素设置 10px 的外边距 */
}

.login-type.active {
  color: #4caf50;
  /* 绿色 */
  font-weight: 500;
  /* 可选：加粗突出 */
}

.el-button:hover {
  background-color: rgb(179, 224.5, 156.5);
  color: #fff;
}

.left-footer {
  margin-top: 30px;
  line-height: 50px;
  color: #808080;
  display: flex;
  gap: 20px;
}

.left-footer span {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
